package utils.msg;

import java.io.IOException;

import model.AlertParameters;
import thread.JavaSmsApi;
import thread.SimpleQueryUtil;
import thread.SmsParameters;

/**
 * 单字段监控信息发送线程，即可以发送短信也可以发送邮件
 * @author zhrb
 *
 */
public class PollingQueryRunnable implements Runnable {
	private AlertParameters ap;
	private SmsParameters smsParams;
	private boolean stop = false;

	public PollingQueryRunnable(AlertParameters ap, SmsParameters smsParams) {
		this.ap = ap;
		this.smsParams = smsParams;
	}
	


	@Override
	public void run() {
		String msg = "";
		while (!stop) {
			RecordModel rm = SimpleQueryUtil.queryFieldForCondition(ap.getUrl().trim(),
					ap.getDrvName().trim(), ap.getUserName(), ap.getUserPwd(),
					ap.getDbName().trim(), ap.getTable().trim(), ap.getField().trim(),
					ap.getCondition().trim(), ap.getTimeSpan(), ap.getThreshold(),
					ap.getQuerycontent(), ap.getCustomTime(), ap.getLocation(),ap.getLocationValue());
			if (rm != null) {
				msg = generateSmsMsg(rm);
				//System.out.println("PollingQueryRunnable.run()，msg="+msg);
				try {
					JavaSmsApi.sendSms(smsParams.getApikey(), msg,smsParams.getMobile());
					String email = ap.getEmail();
					if (email != null && !email.trim().equals("")){//发送邮件
						System.out.println("JavaMail send result="+JavaMail.sendMail(msg, email));
						
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			
			}
			try {
				int interval = ap.getInterval();
				Thread.sleep(interval);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}finally{
				//stopPolling();
			}
		}
	}

	public void stopPolling() {
		this.stop = true;
	}

	public String generateSmsMsg(RecordModel rm) {
		String message = "";
		
	
		message = "【IUE】提醒您:" + rm.getCreateDateTime() + "," + ap.getDbName()
				+ "-" + ap.getTable() + "-" + rm.getLocation() + "-"
				+ ap.getField() + "的值为" + String.format("%.1f",rm.getValue()) + ",超出预警值"
				+ ap.getThreshold();
		//System.out.println(message);
		return message;
	}

}